package com.neusoft.neuiotms.dcom.repository.hn.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.model.enums.HnInspectionCategory;
import com.neusoft.neuiotms.dcom.model.hn.HnInspectionItem;
import com.neusoft.neuiotms.dcom.model.hn.QHnInspectionItem;
import com.neusoft.neuiotms.dcom.repository.hn.CustomizedHnInspectionItemRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedHnInspectionItemRepositoryImpl extends AbstractRepository
        implements CustomizedHnInspectionItemRepository {

    @Override
    public List<HnInspectionItem> index(final Searchable searchable) {
        final QHnInspectionItem qHnInspectionItem = QHnInspectionItem.hnInspectionItem;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<HnInspectionItem> query = this.query().selectFrom(qHnInspectionItem);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<HnInspectionItem> search(final Pageable pageable, final Searchable searchable) {
        final QHnInspectionItem qHnInspectionItem = QHnInspectionItem.hnInspectionItem;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<HnInspectionItem> query = this.query().selectFrom(qHnInspectionItem);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return HnInspectionItem.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {

        final BooleanBuilder where = new BooleanBuilder();
        final QHnInspectionItem qHnInspectionItem = QHnInspectionItem.hnInspectionItem;

        // 名称检索
        if (StringUtils.isNotBlank(searchable.getStrValue("item"))) {
            where.and(super.containsStr(qHnInspectionItem.item, searchable, "item"));
        }

        //巡检分类
        if (!StringUtils.isEmpty(searchable.getStrValue("category"))) {
            where.and((super.equalsEnum(qHnInspectionItem.category, searchable, "category",
                    value -> HnInspectionCategory.valueOf(value))));
        }

        //巡检项类别
        if (StringUtils.isNotBlank(searchable.getStrValue("itemType"))) {
            where.and(super.containsStr(qHnInspectionItem.itemType, searchable, "itemType"));
        }

        // 状态检索
        if (StringUtils.isNotBlank(searchable.getStrValue("disabled"))) {
            where.and(super.equalsBool(qHnInspectionItem.disabled, searchable, "disabled"));
        }

        return where;
    }
}
